import { Plugin } from 'vite'
import MarkdownIt from 'markdown-it'
import hljs from 'highlight.js'
import fs from 'node:fs'
function myPlugin(): Plugin {
  return {
    name: 'vite:myPlugin',
    enforce: 'pre',
    transform(code, id) {
      if (/\.md$/.test(id)) {
        const md = new MarkdownIt({
          highlight(str, lang) {
            if (lang && hljs.getLanguage(lang)) {
              try {
                return hljs.highlight(str, { language: lang }).value
              } catch (__) {}
            }

            return '' // use external default escaping
          },
        })

        const mdFileResult = fs.readFileSync(id).toString()
        const parserResult = md.render(mdFileResult)

        const styleStr = `<style>
        pre {
           background:#eee
            }
          </style>`

        const mdHtml = '`' + parserResult + styleStr + '`'

        return `const code = ${mdHtml}; export default code`
      }

      return code
    },
  }
}

export default myPlugin
